package com.learn.english.controller;

import com.learn.english.domain.R;
import com.learn.english.model.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * @author TISNIW
 * @version 1.0
 * @date 2025/6/20 17:12
 * @desc
 */
@RestController
@RequestMapping("/avatar")
@Tag(name = "头像",description = "提供给用户获取或者修改头像")
public class AvatarController {

    @Value("${path.user.avatar}")
    private String avatarPath;

    /**
     * 获取用户头像接口
     *
     * @param url 头像文件名，例如 "default.png"
     * @return 返回封装后的图片字节流数据
     */
    @GetMapping("/get")
    @Operation(summary = "获取用户头像",description = "返回疯转的图片字节流数据")
    public ResponseEntity<InputStreamResource> getAvatar(@RequestParam String url) throws IOException {
        // 构建完整路径，防止路径穿越攻击
        Path imagePath = Paths.get(avatarPath, url).normalize();

        // 确保访问路径不超出配置目录范围
        if (!imagePath.startsWith(avatarPath)) {
            throw new SecurityException("非法路径访问");
        }

        // 检查文件是否存在，若不存在使用默认头像
        if (!Files.exists(imagePath)) {
            imagePath = Paths.get(avatarPath, "default.png");
            if (!Files.exists(imagePath)) {
                throw new IOException("默认头像文件不存在");
            }
        }
        InputStreamResource resource = new InputStreamResource(Files.newInputStream(imagePath));
        MediaType mediaType = MediaType.parseMediaType(Files.probeContentType(imagePath));

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, mediaType.toString())
                .body(resource);
    }
}